from concurrent.futures import ThreadPoolExecutor
import datetime
import time
import requests
import uvicorn
from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
from account.jie_account_service import JieAccountService

from common.logger import logger
from common.request_limit import allow_request
from manager.proxy_manager import ProxyManager
from model.error import ParkSpiderError, ParkSpiderErrorCode

from spider_handler import TaskRequest
from database.task_table import TaskTable
import spider_handler
import json
from model.dbmodel import DbTaskRecord
from database.task_record_table import TaskRecordsTable

app = FastAPI()

# 设置允许访问的域名
origins = ["*"]  # 也可以设置为"*"，即为所有。

# 设置跨域传参
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 设置允许的origins来源
    allow_credentials=True,
    allow_methods=["*"],  # 设置允许跨域的http方法，比如 get、post、put等。
    allow_headers=["*"],
)  # 允许跨域的headers，可以用来鉴别来源等作用。


def response(e: ParkSpiderError):
    rsp = e.json()
    logger.success(f"response: {rsp}")
    return rsp

@app.post("/api/parkspider/task")
def park_spider_task(data: TaskRequest, request: Request = None):
    logger.info(
        f"request: park_spider_task, host: {request.client.host}, data: {data}"
    )
    if not allow_request(request.client.host, request.url.path, 1000):
        return response(
            ParkSpiderError(ParkSpiderErrorCode.RequestsLimit, request.client.host)
        )
    try:
        spider_handler.task(data)
        return response(ParkSpiderError(ParkSpiderErrorCode.Success))
    except ParkSpiderError as e:
        return response(e)
    except Exception as e:
        return response(ParkSpiderError(ParkSpiderErrorCode.Unknow, repr(e)))

if __name__ == "__main__":
    with TaskTable() as db:
        tasks = db.get_running_tasks()
        for task in tasks:
            logger.warning(f"restart task: {task['id']}")
            spider_handler.task(TaskRequest(task_id=task["id"], options=1))
            with TaskRecordsTable() as db:
                task_record = DbTaskRecord()
                task_record.content = f"系统升级,任务重启"
                task_record.task_id = task["id"]
                task_record.user_id = task["user_id"]
                db.insert(task_record, True)
           
    uvicorn.run(app, host="0.0.0.0", port=3769)
